package com.wang.mall.oauth.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.mall.oauth.bean.SysMenu;
import com.wang.mall.oauth.bean.SysRole;
import com.wang.mall.oauth.mapper.SysMenuMapper;
import com.wang.mall.oauth.service.SysMenuService;
import com.wang.mall.oauth.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {


    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public List<SysMenu> getMenusByUserId(Long userId) {
        // 查询所有的角色
        List<SysRole> sysRoleList = sysRoleService.findByUserId(userId);
        if (CollectionUtils.isEmpty(sysRoleList)) {
            // 没有角色, 就是没有权限, 返回空的权限集合
            return Collections.emptyList();
        }

        List<String> roleNames = sysRoleList.stream().map(SysRole::getRoleName).collect(Collectors.toList());
        if (roleNames.contains("admin")) { // 超级管理员查询所有的权限
            return list();
        }

        List<Long> roleIds = sysRoleList.stream().map(SysRole::getRoleId).collect(Collectors.toList());

        // 有权限, 根据用户ID查询菜单信息
        return baseMapper.findMenuByRoleIds(roleIds);
    }

    @Override
    public List<SysMenu> findMenuByRoleIds(List<Long> roldIds) {
        return baseMapper.findMenuByRoleIds(roldIds);
    }
}
